package com.jp.knowledge.adapter.team_circle;


import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dmcc.image_preview.ImagePreviewActivity;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.ImageActivity;
import com.jp.knowledge.activity.WebBrowserActivity;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.model.TeamCircleModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.base.RecycleVHolder;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.TimeUtil;
import com.jp.knowledge.view.JpRecycleView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TeamCircleAdapter extends RecycleVAdapter<TeamCircleModel> implements View.OnClickListener, View.OnLongClickListener {

    private PopupWindow popupWindow;
    private View popupWindowContentView;
    private TextView payBtn;
    private TextView praiseBtn;
    private TextView commentBtn;
    private View firstLine;

    public TeamCircleAdapter(Context context, @NonNull List<TeamCircleModel> list) {
        super(context, list);
        initPopupWindow();
    }

    private void initPopupWindow(){
        popupWindowContentView = View.inflate(mContext, R.layout.team_circle_item_popupwindow, null);
        payBtn = (TextView) popupWindowContentView.findViewById(R.id.team_circle_pay_reward_tv);
        praiseBtn = (TextView) popupWindowContentView.findViewById(R.id.team_circle_praise_tv);
        commentBtn = (TextView) popupWindowContentView.findViewById(R.id.team_circle_comment_tv);
        firstLine = popupWindowContentView.findViewById(R.id.team_circle_more_first_line);
        payBtn.setOnClickListener(this);
        praiseBtn.setOnClickListener(this);
        commentBtn.setOnClickListener(this);

        popupWindowContentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                popupWindowContentView.getViewTreeObserver().removeOnPreDrawListener(this);
                popupWindow.dismiss();
                View parentView = (View) popupWindowContentView.getTag();
                popupWindow.showAsDropDown(parentView,
                        -popupWindowContentView.getMeasuredWidth()-(int)mContext.getResources().getDimension(R.dimen.space_big),
                        -(popupWindowContentView.getMeasuredHeight()/2)-parentView.getHeight()/2);
                return false;
            }
        });

        popupWindow = new PopupWindow(popupWindowContentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setAnimationStyle(R.style.team_circle_more_popup_window);
    }

    @Override
    public int getLayoutId(int viewType) {
        return R.layout.team_circle_item;
    }

    @Override
    public void onBind(RecycleVHolder holder, int position) {
        final TeamCircleModel model = mList.get(position);
        if(model == null)
            return;
//        ImageLoadUtil.load(context,
//                model.getPortrait() + "?imageView2/2/w/100/interlace/1",
//                holder.getImageView(R.id.team_circle_userIcon),
//                R.mipmap.ic_my_header
//        );
        ImageLoadUtil.loadrund(mContext,
                model.getPortrait() + "?imageView2/2/w/100/interlace/1",
                holder.getImageView(R.id.team_circle_userIcon),
                20, R.mipmap.ic_my_header);
        holder.setTextView(R.id.team_circle_userName, model.getNickname());
//        setLevel(holder.get(R.id.team_circle_level), model.getType(), model.getLevel());
        setLevel(holder.get(R.id.team_circle_level), model.getScoopType(), model.getLevel());
        if(model.getContent() != null && model.getContent().trim().length() > 0) {
            final TextView contentText = holder.getTextView(R.id.team_circle_content);
            final TextView readMoreBtn = holder.getTextView(R.id.team_circle_read_more);
            readMoreBtn.setVisibility(View.GONE);
            readMoreBtn.setTag(position);
            readMoreBtn.setOnClickListener(this);
            contentText.setText(model.getContent());
            View content = holder.get(R.id.team_circle_content);
            content.setTag(position);
            content.setOnLongClickListener(this);
            content.setVisibility(View.VISIBLE);
            content.setOnClickListener(this);
            contentText.setMaxLines(Integer.MAX_VALUE);
            contentText.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    contentText.getViewTreeObserver().removeOnPreDrawListener(this);
                    if(contentText.getLineCount() > 5){
                        if(model.isShowAll()) {
                            readMoreBtn.setText("收起全文");
                        } else{
                            readMoreBtn.setText("展开全文");
                            contentText.setMaxLines(5);
                        }
                        readMoreBtn.setVisibility(View.VISIBLE);
                    }
                    return false;
                }
            });
        } else {
            holder.get(R.id.team_circle_content).setVisibility(View.GONE);
            holder.get(R.id.team_circle_read_more).setVisibility(View.GONE);
        }
        setImgList(holder.get(R.id.team_circle_imgList), model.getImgList());
        setLink(holder.get(R.id.team_circle_link_view), model);
        setInteractive(holder, position);
        setOthers(holder, position);

        setViewGroupTag((ViewGroup)holder.getConvertView(), position);
        holder.get(R.id.team_circle_more).setTag(position);
    }

    private void setViewGroupTag(ViewGroup viewGroup, Object tag){
        viewGroup.setTag(tag);
        for(int i = 0; i < viewGroup.getChildCount(); i++){
            View view = viewGroup.getChildAt(i);
            if(view instanceof ImageView)
                continue;
            if(!(view instanceof ViewGroup)){
                view.setTag(tag);
            } else{
                setViewGroupTag((ViewGroup)view, tag);
            }
        }
    }

    /* 设置级别 */
    protected void setLevel(View levelView, int type, int level){
        ImageView levelIcon = (ImageView) levelView.findViewById(R.id.team_circle_level_icon);
        TextView levelText = (TextView) levelView.findViewById(R.id.team_circle_level_text);
        levelView.setVisibility(View.VISIBLE);
        if(type == 4) {
            levelText.setText(R.string.team_circle_level_topic);
            levelIcon.setImageResource(R.mipmap.grey_words);
            levelText.setTextColor(mContext.getResources().getColor(R.color.font_gray_think));
            return;
        }
        switch (level){
            case 0:
            case 1:
//                levelText.setText(R.string.team_circle_level_normal);
//                levelIcon.setImageResource(R.mipmap.gray_material);
//                levelText.setTextColor(context.getResources().getColor(R.color.font_gray_think));
                levelView.setVisibility(View.GONE);
                break;
            case 2:
                levelText.setText(R.string.team_circle_level_important);
                levelIcon.setImageResource(R.mipmap.gray_material);
                levelText.setTextColor(mContext.getResources().getColor(R.color.font_gray_deep));
                break;
            case 3:
                levelText.setText(R.string.team_circle_level_urgent);
                levelIcon.setImageResource(R.mipmap.red_material);
                levelText.setTextColor(mContext.getResources().getColor(R.color.google_red));
                break;
            default:
                return;
        }
    }

    /* 设置图片列表 */
    private void setImgList(View imgListView, final List<TeamCircleModel.ImgListBean> imgList){
        if(imgList == null || imgList.size() == 0){
            imgListView.setVisibility(View.GONE);
            return;
        }
        imgListView.setVisibility(View.VISIBLE);

        JpRecycleView recyclerView = (JpRecycleView) imgListView;
        if(!recyclerView.hasFixedSize())
            recyclerView.setHasFixedSize(true);
//        int imgCount = imgList.size();
//        if(imgCount == 1 || imgCount == 2 || imgCount == 4){
//            if(recyclerView.getLayoutManager() == null)
//                recyclerView.setLayoutManager(new GridLayoutManager(mContext, 2));
//            else
//                ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanCount(2);
//        } else{
            if(recyclerView.getLayoutManager() == null)
                recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
            else
                ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanCount(3);
//        }

        TeamCircleImgListAdapter adapter = (TeamCircleImgListAdapter) recyclerView.getAdapter();
        final ArrayList<String> imgPaths = new ArrayList<>();
        for (int i = 0; i < imgList.size(); i++) {
            imgPaths.add(imgList.get(i).getSrc());
        }
        if(adapter == null) {
            adapter = new TeamCircleImgListAdapter(mContext, imgList);
            adapter.addItemClickListener(new OnItemClickListener() {
                @Override
                public void itemSelect(int position) {
                    ImagePreviewActivity.startActivity(mContext, position, imgPaths);
                }
            });
            recyclerView.setAdapter(adapter);
        } else{
            adapter.updateAdapter(imgList);
        }
    }

    /* 设置链接视图 */
    private void setLink(View linkView, TeamCircleModel model){
        if(model == null || model.getLinkId() == null || model.getLinkId().trim().length() == 0) {
            linkView.setVisibility(View.GONE);
            return;
        }
        linkView.setVisibility(View.VISIBLE);
        String icon = model.getLinkIcon();
        ImageView  team_icon =  (ImageView) linkView.findViewById(R.id.team_circle_linkIcon);
        if(!TextUtils.isEmpty(icon)) {
            ImageLoadUtil.load(mContext, model.getLinkIcon(),team_icon);
            team_icon.setVisibility(View.VISIBLE);
        }else{
            team_icon.setVisibility(View.GONE);
        }
        ((TextView)linkView.findViewById(R.id.team_circle_linkTitle)).setText(model.getLinkTitle()==null?"":model.getLinkTitle());
        linkView.setOnClickListener(this);
    }

    /* 设置互动 */
    private void setInteractive(RecycleVHolder holder, int position){
        boolean hasPraise = setPraise(holder.get(R.id.team_circle_praise_ly), mList.get(position).getPraise(), position);
        boolean hasPay = setPay(holder.get(R.id.team_circle_pay_ly), mList.get(position).getPayList(), position);
        boolean hasComments = setComments(holder.get(R.id.team_circle_comments), mList.get(position).getComments(), position);
        if(!hasPraise || (!hasPay && !hasComments))
            holder.get(R.id.team_circle_praise_line).setVisibility(View.GONE);
        else
            holder.get(R.id.team_circle_praise_line).setVisibility(View.VISIBLE);
        if(!hasPay || !hasComments)
            holder.get(R.id.team_circle_pay_line).setVisibility(View.GONE);
        else
            holder.get(R.id.team_circle_pay_line).setVisibility(View.VISIBLE);
        if(!hasPraise && !hasPay && !hasComments)
            holder.get(R.id.team_circle_interactive).setVisibility(View.GONE);
        else
            holder.get(R.id.team_circle_interactive).setVisibility(View.VISIBLE);
    }

    /* 设置点赞视图 */
    private boolean setPraise(View praiseView, List<TeamCircleModel.PraiseBean> praiseBeans, int position){
        if(praiseBeans == null || praiseBeans.size() == 0){
            praiseView.setVisibility(View.GONE);
            return false;
        }
        praiseView.setVisibility(View.VISIBLE);
        JpRecycleView recyclerView = (JpRecycleView) praiseView.findViewById(R.id.team_circle_praise);
        if(!recyclerView.hasFixedSize())
            recyclerView.setHasFixedSize(true);
        if(recyclerView.getLayoutManager() == null)
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        TeamCirclePraiseAdapter adapter = (TeamCirclePraiseAdapter) recyclerView.getAdapter();
        if(adapter == null) {
            adapter = new TeamCirclePraiseAdapter(mContext, praiseBeans);
            recyclerView.setAdapter(adapter);
        } else{
            adapter.updateAdapter(praiseBeans);
        }
        return true;
    }

    /* 设置支付视图 */
    private boolean setPay(View payView, List<TeamCircleModel.PraiseBean> payBeans, int position){
        if(payBeans == null || payBeans.size() == 0){
            payView.setVisibility(View.GONE);
            return false;
        }
        payView.setVisibility(View.VISIBLE);
        JpRecycleView recyclerView = (JpRecycleView) payView.findViewById(R.id.team_circle_pay);
        if(!recyclerView.hasFixedSize())
            recyclerView.setHasFixedSize(true);
        if(recyclerView.getLayoutManager() == null)
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        TeamCirclePraiseAdapter adapter = (TeamCirclePraiseAdapter) recyclerView.getAdapter();
        if(adapter == null) {
            adapter = new TeamCirclePraiseAdapter(mContext, payBeans);
            recyclerView.setAdapter(adapter);
        } else{
            adapter.updateAdapter(payBeans);
        }
        return true;
    }

    /* 设置评论视图 */
    private boolean setComments(View view, List<TeamCircleModel.CommentsBean> comments, int position){
        if(comments == null || comments.size() == 0){
            view.setVisibility(View.GONE);
            return false;
        }
        view.setVisibility(View.VISIBLE);
        JpRecycleView commentsView = (JpRecycleView)view;
        if(!commentsView.hasFixedSize())
            commentsView.setHasFixedSize(true);
        if(commentsView.getLayoutManager() == null)
            commentsView.setLayoutManager(new LinearLayoutManager(mContext));
        TeamCircleCommentsAdapter adapter = (TeamCircleCommentsAdapter) commentsView.getAdapter();
        if(adapter == null) {
            adapter = new TeamCircleCommentsAdapter(mContext, comments, position);
            adapter.setCommentClickListener(new TeamCircleCommentsAdapter.OnCommentClickListener() {
                @Override
                public void onCommentClick(int parentPosition, int position) {
                    if (viewClickListener != null) {
                        viewClickListener.onCommentItemClick(parentPosition, position);
                    }
                }
            });
            commentsView.setAdapter(adapter);
        } else{
            adapter.setParentPosition(position);
            adapter.updateAdapter(comments);
        }
        return true;
    }

    /* 设置其他视图，如时间，回复数，点赞数等 */
    private void setOthers(RecycleVHolder holder, int position){
        if(mList.get(position).getType() == 4){
            holder.get(R.id.team_circle_more).setVisibility(View.GONE);
        } else {
            holder.get(R.id.team_circle_more).setVisibility(View.VISIBLE);
            holder.get(R.id.team_circle_more).setOnClickListener(this);
        }

        TextView sendTimeTv = holder.getTextView(R.id.team_circle_time);
        try {
            sendTimeTv.setText(TimeUtil.friendly_time(mList.get(position).getTime()));
            sendTimeTv.setVisibility(View.VISIBLE);
        } catch (Exception e){
            sendTimeTv.setVisibility(View.GONE);
        }
        holder.getImageView(R.id.team_circle_private).setVisibility(mList.get(position).getVisibility()==2?View.VISIBLE:View.GONE);
        List<TeamCircleModel.CommentsBean> comments = mList.get(position).getComments();
        if(comments == null || comments.size() == 0){
            holder.get(R.id.team_circle_chat).setVisibility(View.GONE);
        } else {
            Set<String> commentUids = new HashSet<>();
            for(TeamCircleModel.CommentsBean commentsBean : comments){
                commentUids.add(commentsBean.getUid());
            }
            holder.get(R.id.team_circle_chat).setVisibility(View.VISIBLE);
            holder.setTextView(R.id.team_circle_chat, String.format(mContext.getString(R.string.team_circle_comment_count), commentUids.size()));
        }
        holder.get(R.id.team_circle_pay_reward).setVisibility(View.GONE);
        holder.get(R.id.team_circle_delete).setOnClickListener(this);
        JpApplication application = (JpApplication) mContext.getApplicationContext();
        if(application.getUserData() != null && application.getUserData().getUuid() != null){
            String userUuid = application.getUserData().getUuid();
            if(userUuid.equals(mList.get(position).getUserId())) {
                holder.get(R.id.team_circle_delete).setVisibility(View.VISIBLE);
            } else{
                holder.get(R.id.team_circle_delete).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()){
            case R.id.team_circle_more:                   // 在 item 中点击更多
                int index = (int)v.getTag();
                praiseBtn.setTag(index);
                payBtn.setTag(index);
                commentBtn.setTag(index);

                if(mList.get(index).getIsPraise() == 1)
                    praiseBtn.setText(R.string.team_circle_popupwindow_praise_cancel);
                else
                    praiseBtn.setText(R.string.team_circle_popupwindow_praise);
                if(mList.get(index).getIsPay() == 1){
                    payBtn.setText("已赏");
                    payBtn.setTextColor(mContext.getResources().getColor(R.color.gray_bg));
                } else{
                    payBtn.setText("赏");
                    payBtn.setTextColor(mContext.getResources().getColor(R.color.white));
                }
                JpApplication application = (JpApplication) mContext.getApplicationContext();
                if(application.getUserData() != null && application.getUserData().getUuid() != null){
                    String userUuid = application.getUserData().getUuid();
                    if(userUuid.equals(mList.get(index).getUserId())) {
                        payBtn.setVisibility(View.GONE);
                        firstLine.setVisibility(View.GONE);
                    } else{
                        payBtn.setVisibility(View.VISIBLE);
                        firstLine.setVisibility(View.VISIBLE);
                    }
                }
                popupWindowContentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                popupWindowContentView.setTag(v);
                popupWindow.showAsDropDown(v,
                        -popupWindowContentView.getMeasuredWidth()-(int)mContext.getResources().getDimension(R.dimen.space_big),
                        -(popupWindowContentView.getMeasuredHeight()/2)-v.getHeight()/2);
                break;
            case R.id.team_circle_pay_reward_tv:        // 赏
                popupWindow.dismiss();
                if(this.viewClickListener != null)
                    this.viewClickListener.onPayRewardClick((int) v.getTag());
                break;
            case R.id.team_circle_praise_tv:            // 赞
                popupWindow.dismiss();
                if(this.viewClickListener != null)
                    this.viewClickListener.onPraiseClick((int) v.getTag());
                break;
            case R.id.team_circle_comment_tv:           // 评论
                popupWindow.dismiss();
                if(this.viewClickListener != null)
                    this.viewClickListener.onCommentClick((int) v.getTag());
                break;
            case R.id.team_circle_link_view:            // 单击链接跳转到详情
//                Intent intent = new Intent(context, InfoDataDetail.class);
                TeamCircleModel model = mList.get((int) v.getTag());
                if(mList.get((int)v.getTag()).getLinkType() == 15){
                    WebBrowserActivity.openWebActivity(mContext, model.getLinkIcon());
                } else {
                    Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
                    intent.putExtra("id", model.getLinkId());
                    intent.putExtra("type", model.getLinkType());
                    intent.putExtra("linkIcon", model.getLinkIcon());
                    intent.putExtra("linkTitle", model.getLinkTitle());
                    mContext.startActivity(intent);
                }
                break;
            case R.id.team_circle_delete:               // 删除
                if(this.viewClickListener != null)
                    this.viewClickListener.onItemDeleteClick((int)v.getTag());
                break;
            case R.id.team_circle_content:
                if(mOnItemClickListener != null)
                    mOnItemClickListener.itemSelect((int) v.getTag());
                break;
            case R.id.team_circle_read_more:
                int position = (int) v.getTag();
                TeamCircleModel data = getData(position);
                data.setShowAll(!data.isShowAll());
                notifyItemChanged(position);
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if(this.viewClickListener != null)
            this.viewClickListener.onContextLongClick((int) v.getTag());
        return false;
    }

    protected TeamCircleViewClickListener viewClickListener;
    public void setViewClickListener(TeamCircleViewClickListener listener){
        this.viewClickListener = listener;
    }

    public interface TeamCircleViewClickListener {
        void onItemDeleteClick(int position);
        void onCommentItemClick(int parentPosition, int position);
        void onPayRewardClick(int position);
        void onPraiseClick(int position);
        void onCommentClick(int position);
        void onContextLongClick(int position);
    }
}
